import { UserInfoVO } from '@/entiy/vo/UserInfoVO.ts';
import RequestService from '@/service/RequestService.ts';
import { LoginFormData } from '@/entiy/form/LoginFormData.ts';
import { defineStore } from 'pinia';
import PromiseUtils from "@/utils/PromiseUtils.ts";
import { LoginResultVO } from "@/entiy/vo/LoginResultVO.ts";
import {BizResultUtils} from "@/utils/BizResultUtils.ts";

export const useUserStore = defineStore('userStore', {
    state: () => {
        return {
            token:null as string | null,
            userInfo: null as UserInfoVO | null
        };
    },

    // 开启持久化保存
    persist: true,

    getters: {
        loginStatus(state) {
            return state.token !== null && state.userInfo !== null;
        },
    },

    actions: {

        /**
         * 用户登录
         *
         * @param formData 登录表单数据
         */
        async login(formData: LoginFormData): Promise<void> {
            const bizResult = await RequestService.post<LoginResultVO>('/anonymous/login-by-password', formData);
            if (BizResultUtils.isError(bizResult)) {
                return PromiseUtils.reject(bizResult.errorMsg);
            }

            // 登录成功设置登录状态
            const bizDta = bizResult.bizData;
            this.token = bizDta.token;
            this.userInfo = bizDta.baseUserInfo;
        },

        /**
         * 退出登陆
         */
        async logout(): Promise<void> {
            try {
                await RequestService.post('/logout', {});
            } finally {
                this.token = null;
                this.userInfo = null;
            }
        },
    }
});
